<!--  -->
<template>
  <div>
    <div
      class="multi-detail"
      v-drag
      v-show="multiDetailVisible"
      ref="multiDetailDialog"
    >
      <template
        v-show="
          multiDetailVisible && multiDetailIndex !== -1
        "
      >
        <div class="multi-detail-header">
          <span class="multi-detail-header-title">{{
            multiDetailData[multiDetailIndex]
              ? multiDetailData[multiDetailIndex].title
              : ''
          }}</span>
          <i
            class="el-icon-close multi-detail-header-close"
            @click="closeMultiDetail"
          />
        </div>

        <div class="multi-detail-header-right">
          <Icon
            class="icon"
            :class="
              multiDetailIndex !== 0 ? 'enable' : 'disable'
            "
            title="上一个"
            name="west"
            font-size="20"
            :color="
              multiDetailIndex !== 0
                ? 'rgba(0, 210, 255, 1)'
                : '#A7BECA'
            "
            @click.native="
              changeMultiDetailIndex('previous')
            "
          />
          <Icon
            class="icon"
            :class="
              multiDetailIndex !==
              multiDetailData.length - 1
                ? 'enable'
                : 'disable'
            "
            title="下一个"
            name="east"
            font-size="20"
            :color="
              multiDetailIndex !==
              multiDetailData.length - 1
                ? 'rgba(0, 210, 255, 1)'
                : '#A7BECA'
            "
            @click.native="changeMultiDetailIndex('next')"
          />
        </div>

        <div
          class="multi-detail-content"
          v-if="multiDetailData[multiDetailIndex]"
        >
          <el-scrollbar>
            <div
              class="can-copy-content"
              @copy="copyProperty"
            >
              <div
                class="multi-detail-content-item"
                v-for="(value, name) in multiDetailData[
                  multiDetailIndex
                ].detailData"
                :key="name"
              >
                <span
                  v-if="
                    name.indexOf('SM') === -1 &&
                    name.indexOf('Sm') === -1 &&
                    name.indexOf('sm') === -1
                  "
                  class="name"
                  >{{
                    (name || '') + ':\t' + (value || '')
                  }}
                </span>
                <!--                <span-->
                <!--                  v-if="-->
                <!--                  (name.indexOf('SM') === -1) &-->
                <!--                    (name.indexOf('Sm') === -1) &&-->
                <!--                  name.indexOf('sm') === -1-->
                <!--                "-->
                <!--                  class="value"-->
                <!--                >{{ value || '' }}</span-->
                <!--                >-->
              </div>
            </div>
          </el-scrollbar>
          <!--          v-if="multiDetailData[multiDetailIndex].layerId"-->
          <div class="button-box">
            <!-- <el-button
              size="small"
              type="primary"
              @click="viewDetailOfLayerProperty"
              :class="{
                disable:
                  !multiDetailData[multiDetailIndex].layerId
              }"
              >查看详情
            </el-button> -->
            <el-button @click="zoomPositioning"
              >缩放定位
            </el-button>
          </div>
        </div>
      </template>
    </div>
    <!-- 属性详情弹框 -->
    <div
      class="property-detail"
      v-if="propertyDetailVisible"
    >
      <div class="property-detail-header">
        <div class="property-detail-header-left">
          <span class="property-detail-header-left-title">
            {{
              multiDetailData[multiDetailIndex].title || ''
            }}
          </span>

          <div class="tab">
            <div
              v-for="(item, index) in propertyDetailTabs"
              class="tab-item"
              :key="item"
              :class="{
                active:
                  index === currentPropertyDetailTabIndex
              }"
              @click="currentPropertyDetailTabIndex = index"
            >
              <span class="tab-item-title">
                {{ item }}
              </span>
            </div>
          </div>
        </div>

        <i
          class="el-icon-circle-close close"
          @click="closePropertyDetail"
        />
      </div>

      <div class="property-detail-body">
        <!-- 属性 -->
        <el-scrollbar
          v-if="currentPropertyDetailTabIndex === 0"
        >
          <div
            class="multi-detail-content-item"
            v-for="(value, name) in multiDetailData[
              multiDetailIndex
            ].detailData"
            :key="name"
          >
            <span
              v-if="
                name.indexOf('SM') === -1 &&
                name.indexOf('Sm') === -1 &&
                name.indexOf('sm') === -1
              "
              class="name"
              >{{ name || '' }}:
            </span>
            <span
              v-if="
                name.indexOf('SM') === -1 &&
                name.indexOf('Sm') === -1 &&
                name.indexOf('sm') === -1
              "
              class="value"
              >{{ value || '' }}</span
            >
          </div>
        </el-scrollbar>

        <!-- 附件 -->
        <div
          v-if="currentPropertyDetailTabIndex === 1"
          class="attachment-container"
        >
          <div
            class="left"
            v-if="currentAttachmentStageIndex !== -1"
          >
            <el-scrollbar
              v-if="propertyDetailAttachments.length"
            >
              <div
                v-for="(
                  stage, index
                ) in propertyDetailAttachments.map(
                  (item) => item.catalogName
                )"
                class="stage"
                :key="index"
                :class="{
                  active:
                    index === currentAttachmentStageIndex
                }"
                @click="changeStageIndex(index)"
              >
                <span>{{ stage }}</span>
              </div>
            </el-scrollbar>
          </div>
          <div
            class="right"
            v-if="currentAttachmentStageIndex !== -1"
          >
            <el-scrollbar
              v-if="propertyDetailAttachments.length"
            >
              <div
                v-for="(
                  item, index
                ) in propertyDetailAttachments[
                  currentAttachmentStageIndex
                ].children"
                class="node"
                :key="index"
              >
                <div class="node-name">
                  <div class="prefix"></div>
                  <span>{{ item.catalogName }}</span>
                </div>

                <div
                  v-for="(
                    childItem, childIndex
                  ) in propertyDetailAttachments[
                    currentAttachmentStageIndex
                  ].children[index].resourceInfo"
                  class="node-child"
                  :class="{ first: childIndex === 0 }"
                  :key="childIndex"
                  @click="attachmentItemClick(childItem)"
                >
                  <el-link
                    :title="childItem.attachmentName"
                  >
                    <i class="el-icon-notebook-2" />
                    <span>
                      {{ childItem.attachmentName }}
                    </span>
                  </el-link>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>

        <!-- 图片 -->
        <el-scrollbar
          v-if="
            currentPropertyDetailTabIndex === 2 &&
            Object.keys(propertyDetailFlattenPictures)
              .length
          "
        >
          <div
            v-for="item in Object.keys(
              propertyDetailFlattenPictures
            )"
            :key="item"
            class="picture"
          >
            <div class="picture-header">
              <div class="prefix"></div>
              <span class="type">{{ item }}</span>
              <span class="count"
                >共&nbsp;{{
                  propertyDetailFlattenPictures[item]
                    .length
                }}&nbsp;张</span
              >
            </div>

            <div class="picture-list">
              <div
                v-for="childItem in propertyDetailFlattenPictures[
                  item
                ]"
                :key="childItem.pkid"
                class="picture-list-item"
                @click="clickImageItem(childItem)"
              >
                <el-image
                  :src="childItem.imageSrc"
                  fit="cover"
                />

                <span class="time">{{
                  formatTime(
                    childItem.releaseTime,
                    'YYYY-MM-DD'
                  )
                }}</span>

                <span class="introduction">{{
                  childItem.remark
                }}</span>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script>
import Icon from '@/components/icon'
import * as turf from '@turf/turf'
import New from '@/utils/new'
import {
  queryAllAttachment,
  queryAllPicture,
  retrieveDataServiceList
} from '@/api/multiple-dataservice'
import { noticeFileDownload } from '@/api/wisdomBuild'

import { getAction } from '@/utils/helper'
let clickHandler
let _layerManager
const mapViewer = {}
let previousGeojsonList = []

export default {
  props: {
    viewerId: {
      type: String,
      default: 'defaultViewId'
    }
  },
  components: {
    Icon
  },
  data() {
    return {
      lastClickedPosition: [],
      multiDetailVisible: false,
      multiDetailData: [],
      multiDetailIndex: -1,
      propertyDetailVisible: false, // 属性详情弹框显示
      propertyDetailTabs: ['属性', '附件', '图片'],
      currentPropertyDetailTabIndex: -1,
      propertyDetailAttachments: [], // 属性详情附件
      propertyDetailPictures: [], // 属性详情图片
      propertyDetailFlattenPictures: {}
    }
  },
  watch: {
    multiDetailVisible(val) {
      if (val) {
        this.calculateMultiDetailDialogPosition()
      }
      // if (val && this.multiDetailIndex !== -1) {
      //   this.$bus.$emit(
      //     'handleDetailData',
      //     true,
      //     this.multiDetailData,
      //     this.multiDetailIndex
      //   )
      // } else if (!val) {
      //   this.$bus.$emit('handleDetailData', false)
      // }
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（访问DOM元素）
  async mounted() {
    this.onMapLoad()
  },
  methods: {
    async onMapLoad() {
      const { viewer, layerManager } = await getAction(
        this.viewerId
      )
      _layerManager = layerManager
      mapViewer[this.viewerId] = viewer
      const id = this.viewerId
      clickHandler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene.canvas
      )
      clickHandler.setInputAction(async (e) => {
        this.lastClickedPosition = [
          e.position.x,
          e.position.y
        ]
        // if (this.customAreaDrawActived) {
        //   return
        // }
        // if (this.$route.path.indexOf('/cockpit/iot') !== -1) {
        //   // 在万物互联下点击
        //   const pick = viewer.scene.pick(e.position)
        //   if (Cesium.defined(pick) && pick.id.id) {
        //     this.$bus.$emit('clickEntity', pick.id.id)
        //   }
        // }
        const cartesian = mapViewer[
          id
        ].camera.pickEllipsoid(
          e.position,
          viewer.scene.globe.ellipsoid
        )
        const cartographic =
          Cesium.Cartographic.fromCartesian(cartesian)
        this.cartographic = cartographic
        console.log(
          'clicked',
          Cesium.Math.toDegrees(cartographic.longitude),
          Cesium.Math.toDegrees(cartographic.latitude),
          cartographic.height
        )

        // this.closeMultiDetail()
        // this.closeVideo()

        const zoomLevel = this.getZoomLevel(viewer)
        if (zoomLevel < 12) {
          // 镜头过远，不执行查询操作
          return
        }
        let distance
        switch (zoomLevel) {
          case 12:
            distance = 0.0005
            break
          case 13:
            distance = 0.0003
            break
          case 14:
            distance = 0.0001
            break
          case 15:
            distance = 0.00009
            break
          case 16:
            distance = 0.00005
            break
          default:
            distance = 0.00003
            break
        }
        const existedAndShownLayers =
          _layerManager.layers.filter(
            (item) =>
              // item.type === 'imagery' && item.layer.show
              item.serviceType !== '27' &&
              item.layer.show &&
              item.currentDataIndex >= 0 &&
              item.dataList.length &&
              item.dataList[item.currentDataIndex] &&
              item.dataList[item.currentDataIndex]
                .resourceServiceDataInfoList.length
          )
        console.log(
          'existedAndShownLayers',
          existedAndShownLayers
        )
        await this.retrievePropertiesByPoint(
          viewer,
          existedAndShownLayers,
          [
            Cesium.Math.toDegrees(cartographic.longitude),
            Cesium.Math.toDegrees(cartographic.latitude)
          ],
          distance
        )
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    getZoomLevel(viewer) {
      const h = viewer.camera.positionCartographic.height
      if (h <= 100) {
        return 19
      } else if (h <= 300) {
        return 18
      } else if (h <= 660) {
        return 17
      } else if (h <= 1300) {
        return 16
      } else if (h <= 2600) {
        return 15
      } else if (h <= 6400) {
        return 14
      } else if (h <= 13200) {
        return 13
      } else if (h <= 26000) {
        return 12
      } else if (h <= 67985) {
        return 11
      } else if (h <= 139780) {
        return 10
      } else if (h <= 250600) {
        return 9
      } else if (h <= 380000) {
        return 8
      } else if (h <= 640000) {
        return 7
      } else if (h <= 1280000) {
        return 6
      } else if (h <= 2600000) {
        return 5
      } else if (h <= 6100000) {
        return 4
      } else if (h <= 11900000) {
        return 3
      } else {
        return 2
      }
    },
    // 根据点查询属性
    async retrievePropertiesByPoint(
      viewer,
      serviceList,
      point,
      radius
    ) {
      for await (const service of serviceList) {
        // console.log('service', service)
        for await (const dataService of service.dataList[
          service.currentDataIndex
        ].resourceServiceDataInfoList) {
          // console.log('dataService', dataService)
          // console.log('请求', dataService.serviceDataUrl, point)
          const circle = turf.circle(point, radius * 300, {
            units: 'kilometers'
          })
          // const buffer = turf.buffer(turf.point(point), radius, { units: 'kilometers' })
          const polygon = L.polygon([
            ...circle.geometry.coordinates[0].map(
              (item) => {
                return [item[1], item[0]]
              }
            )
          ])
          const queryUrl =
            dataService.serviceDataUrl.substring(
              0,
              dataService.serviceDataUrl.lastIndexOf(
                '/datasources/'
              )
            )
          const dataSourceAndDataSet =
            dataService.serviceDataUrl
              .substring(
                dataService.serviceDataUrl.lastIndexOf(
                  '/datasources/'
                ) + '/datasources/'.length
              )
              .split('/datasets/')
              .map((item) => decodeURI(item))
          const param =
            new SuperMap.GetFeaturesByGeometryParameters({
              datasetNames: [
                `${dataSourceAndDataSet.join(':')}`
              ],
              geometry: polygon,
              spatialQueryMode:
                SuperMap.SpatialQueryMode.INTERSECT,
              fromIndex: 0,
              toIndex: -1
            })
          const properties = await this.queryBySql(
            viewer,
            queryUrl,
            param
          )
          if (properties) {
            // console.log('查询属性结果', properties)
            // console.log(
            //   'multiDetailData',
            //   this.multiDetailData
            // )
            const findIndex =
              this.multiDetailData.length > 0
                ? this.multiDetailData.findIndex(
                    (item) => item.layerId === service.id
                  )
                : -1
            if (findIndex !== -1) {
              this.multiDetailData.splice(findIndex, 1, {
                title: `${service.name}(${dataService.name})`,
                layerId: service.id,
                dataServiceId: dataService.pkid,
                detailData: properties
              })
            } else {
              this.multiDetailData.push({
                title: `${service.name}(${dataService.name})`,
                layerId: service.id,
                dataServiceId: dataService.pkid,
                detailData: properties
              })
            }
          }
        }
      }
      if (this.multiDetailData.length > 0) {
        this.multiDetailIndex =
          this.multiDetailData.length - 1
        this.multiDetailVisible = true
        this.calculateMultiDetailDialogPosition()
      }
    },
    queryBySql(viewer, queryUrl, param) {
      return new Promise((resolve) => {
        L.supermap
          .featureService(queryUrl)
          .getFeaturesByGeometry(param, (result) => {
            if (result.error) {
              this.$message.error(
                result.error.errorMsg || '范围查询失败'
              )
              resolve(null)
            }
            if (result.result.featureCount > 0) {
              const feature =
                result.result.features.features[0]
              Cesium.GeoJsonDataSource.load(feature, {
                markerSize: 0,
                clampToGround: true
              }).then((dataSource) => {
                viewer.dataSources.add(dataSource)
                previousGeojsonList.push(dataSource)
                const entities = dataSource.entities.values
                entities.forEach((entity) => {
                  if (entity.polygon) {
                    entity.polygon.extrudedHeight = 0.1
                    entity.polygon.material =
                      Cesium.Color.WHITE.withAlpha(0.3)
                    entity.polygon.outlineWidth = 3
                    entity.polygon.outlineColor =
                      Cesium.Color.WHITE.withAlpha(0.3)
                  } else if (entity.polyline) {
                    // console.log(
                    //   'positions',
                    //   entity.polyline
                    //     .positions
                    // )
                    entity.polyline.material =
                      Cesium.Color.WHITE.withAlpha(0.7)
                    entity.polyline.width = 5
                  } else if (entity.point) {
                    // console.log(
                    //   'the entity has point'
                    // )
                  } else {
                    // entity.show = false
                    entity.point = new Cesium.PointGraphics(
                      {
                        color:
                          Cesium.Color.WHITE.withAlpha(0.5),
                        pixelSize: 10,
                        outlineWidth: 2,
                        outlineColor: Cesium.Color.RED,
                        heightReference:
                          Cesium.HeightReference
                            .CLAMP_TO_GROUND
                      }
                    )
                    // console.log(
                    //   entity.point
                    // )
                  }
                })
                // console.log(
                //   'previousGeojsonList',
                //   previousGeojsonList
                // )
              })
              // const tempProperties = {}
              // Object.keys(feature.properties).forEach(
              //   (key) => {
              //     if (
              //       key.startsWith('Sm') ||
              //       key.startsWith('SM') ||
              //       key.startsWith('sm')
              //     ) {
              //       return
              //     }
              //     tempProperties[key] =
              //       feature.properties[key]
              //   }
              // )
              // resolve(tempProperties)
              resolve(feature.properties)
            } else {
              resolve(null)
            }
          })
      })
    },
    changeMultiDetailIndex(type) {
      if (type === 'previous') {
        if (
          this.multiDetailIndex !== 0 &&
          this.multiDetailIndex !== -1
        ) {
          this.multiDetailIndex -= 1
        }
      } else {
        if (
          this.multiDetailIndex !==
            this.multiDetailData.length - 1 &&
          this.multiDetailIndex !== -1
        ) {
          this.multiDetailIndex += 1
        }
      }
    },
    calculateMultiDetailDialogPosition() {
      const { innerWidth, innerHeight } = window
      const orientation = {}
      if (this.lastClickedPosition[0] + 410 >= innerWidth) {
        orientation.horizontal = 'left'
      } else {
        orientation.horizontal = 'right'
      }
      if (
        this.lastClickedPosition[1] + 350 >=
        innerHeight
      ) {
        orientation.vertical = 'top'
      } else {
        orientation.vertical = 'bottom'
      }
      // console.log(this.lastClickedPosition)
      if (orientation.horizontal === 'left') {
        this.$refs.multiDetailDialog.style.setProperty(
          'left',
          `${this.lastClickedPosition[0] - 410}px`
        )
      } else {
        this.$refs.multiDetailDialog.style.setProperty(
          'left',
          `${this.lastClickedPosition[0]}px`
        )
      }
      if (orientation.vertical === 'top') {
        this.$refs.multiDetailDialog.style.setProperty(
          'top',
          `${this.lastClickedPosition[1] - 350}px`
        )
      } else {
        this.$refs.multiDetailDialog.style.setProperty(
          'top',
          `${this.lastClickedPosition[1]}px`
        )
      }
    },
    closeMultiDetail() {
      this.multiDetailVisible = false
      if (
        this.$route.path.indexOf('/cockpit/iot') === -1 &&
        this.$route.path.indexOf('/cockpit/growth') === -1
      ) {
        // 如果不是在万物互联或者生长动态中点击关闭
        New.$off('projectShow')
      }
      this.multiDetailIndex = -1
      this.multiDetailData = []
      this.closePropertyDetail()
      previousGeojsonList.forEach((item) => {
        mapViewer[this.viewerId].dataSources.remove(item)
      })
      previousGeojsonList = []
    },
    closePropertyDetail() {
      this.propertyDetailVisible = false
      if (
        this.$route.path.indexOf('/cockpit/iot') === -1 &&
        this.$route.path.indexOf('/cockpit/growth') === -1
      ) {
        // 如果不是在万物互联或者生长动态中点击关闭
        New.$off('projectShow')
      }
      this.currentPropertyDetailTabIndex = -1
      this.propertyDetailAttachments = []
      this.propertyDetailPictures = []
      this.propertyDetailFlattenPictures = {}
      this.currentAttachmentStageIndex = -1
    },
    getSelectedLayer() {
      const layers =
        mapViewer[this.defaultViewId].scene.layers._layers
          .values
      const layerCount = layers.length
      if (layerCount > 0) {
        for (let i = 0; i < layerCount; i++) {
          const ids = layers[i].getSelection()
          if (ids[0]) {
            // console.log('layer', layers[i])
            // console.log('id', ids[0])
            return layers[i]
          } else {
            return null
          }
        }
        return null
      } else {
        return null
      }
    },
    resolvePictures(list) {
      list.forEach((item) => {
        const type = item.catalogName
        if (!this.propertyDetailFlattenPictures[type]) {
          this.propertyDetailFlattenPictures[type] = []
        }
        item.pictureInfoList.forEach((picture) => {
          this.propertyDetailFlattenPictures[type].push(
            picture
          )
          this.downloadImage(picture)
        })
      })
    },
    downloadImage(e) {
      noticeFileDownload(e.fileId)
        .then((res) => {
          const reader = new FileReader()
          reader.readAsDataURL(res)
          reader.onloadend = () => {
            e.imageSrc = reader.result
            this.propertyDetailPictures.forEach((item) => {
              item.childList.forEach((child) => {
                if (child.pkid === e.fileId) {
                  child.imageSrc = reader.result
                }
              })
            })
          }
        })
        .catch((err) => {
          console.error(err)
        })
    },
    // 查看图层属性详情
    async viewDetailOfLayerProperty() {
      if (
        this.$route.path.indexOf('/cockpit/iot') === -1 &&
        this.$route.path.indexOf('/cockpit/growth') === -1
      ) {
        // 如果不是在万物互联或者生长动态中点击查看详情
        New.$on('projectShow', (data) => {
          if (!data) {
            this.propertyDetailVisible = false
          } else {
            this.propertyDetailVisible = true
          }
        })
      }
      if (
        !this.multiDetailData[this.multiDetailIndex].layerId
      ) {
        if (
          this.$route.path.indexOf('/cockpit/growth') !== -1
        ) {
          // 如果再生长动态中点击查看详情
          this.multiDetailVisible = false
          this.$bus.$emit(
            'viewDetail',
            this.multiDetailData[this.multiDetailIndex]
              .detailData['SMID']
          )
          return
        }
        const selectedLayer = this.getSelectedLayer()
        console.log('selectedLayer', selectedLayer)
        if (selectedLayer) {
          const allLayers = _layerManager.layers.filter(
            (item) => item.type === 'layer'
          )
          console.log('alllayers', allLayers)
          const currentLayer = allLayers.find(
            (item) =>
              item.layer.find(
                (item2) => item2 === selectedLayer
              ) !== undefined
          )
          console.log('currentLayer', currentLayer)
          if (currentLayer) {
            const multiDataServiceList =
              currentLayer.dataList[
                currentLayer.currentDataIndex
              ].resourceServiceDataInfoList
            console.log(
              'multiDataServiceList',
              multiDataServiceList
            )
            if (multiDataServiceList.length) {
              // const dataService = multiDataServiceList.find(
              //   (item) =>
              //     item.pkid ===
              //     this.multiDetailData[this.multiDetailIndex]
              //       .dataServiceId
              // )
              const dataService = multiDataServiceList[0]
              if (dataService) {
                const id = dataService.pkid
                const attributeWord =
                  dataService.attributeWord
                const detailData =
                  this.multiDetailData[
                    this.multiDetailIndex
                  ].detailData
                let key = ''
                for (const item of Object.keys(
                  detailData
                )) {
                  if (
                    item.toLowerCase() ===
                    attributeWord.toLowerCase()
                  ) {
                    key = item
                  }
                }
                await queryAllAttachment({
                  type: `${id}--${detailData[key]}`
                  // serviceDataId: id,
                  // serviceAttributeValue: detailData[key]
                }).then((res) => {
                  if (
                    res.success &&
                    res.data &&
                    res.data.length
                  ) {
                    this.propertyDetailAttachments =
                      res.data[0].children
                    this.currentAttachmentStageIndex = 0
                    console.log(
                      '附件',
                      res.data[0].children
                    )
                  }
                })
                await queryAllPicture({
                  type: `${id}__${detailData[key]}`
                  // serviceDataId: id,
                  // serviceAttributeValue: detailData[key]
                }).then((res) => {
                  if (
                    res.success &&
                    res.data &&
                    res.data.length
                  ) {
                    this.resolvePictures(
                      res.data[0].children
                    )
                    const tempList = []
                    res.data[0].children.forEach((item) => {
                      item.pictureInfoList.forEach(
                        (child) => {
                          child.pictureType =
                            item.catalogName
                          tempList.push(child)
                        }
                      )
                    })
                    this.propertyDetailPictures = tempList
                    console.log('图片', res.data)
                    console.log(
                      'flatten',
                      this.propertyDetailFlattenPictures
                    )
                  }
                })
                this.multiDetailVisible = false
                this.propertyDetailVisible = true
                this.currentPropertyDetailTabIndex = 0
              } else {
                this.$message.error('无数据服务配置')
              }
            } else {
              this.$message.error('无数据服务配置')
            }
          }
        }
        // this.multiDetailVisible = false
        // this.propertyDetailVisible = true
        // this.currentPropertyDetailTabIndex = 0
      } else {
        console.log(
          '查看属性详情',
          this.multiDetailData[this.multiDetailIndex]
        )
        const currentLayer = _layerManager.get(
          this.multiDetailData[this.multiDetailIndex]
            .layerId
        )
        console.log('currentLayer', currentLayer)
        const multiDataServiceList =
          currentLayer.dataList[
            currentLayer.currentDataIndex
          ].resourceServiceDataInfoList
        console.log(
          'multiDataServiceList',
          multiDataServiceList
        )
        if (multiDataServiceList.length) {
          const dataService = multiDataServiceList.find(
            (item) =>
              item.pkid ===
              this.multiDetailData[this.multiDetailIndex]
                .dataServiceId
          )
          if (dataService) {
            const id = dataService.pkid
            const attributeWord = dataService.attributeWord
            const detailData =
              this.multiDetailData[this.multiDetailIndex]
                .detailData
            let key = ''
            for (const item of Object.keys(detailData)) {
              if (
                item.toLowerCase() ===
                attributeWord.toLowerCase()
              ) {
                key = item
              }
            }
            await queryAllAttachment({
              type: `${id}--${detailData[key]}`
              // serviceDataId: id,
              // serviceAttributeValue: detailData[key]
            }).then((res) => {
              if (
                res.success &&
                res.data &&
                res.data.length
              ) {
                this.propertyDetailAttachments =
                  res.data[0].children
                this.currentAttachmentStageIndex = 0
                console.log('附件', res.data[0].children)
              }
            })
            await queryAllPicture({
              type: `${id}__${detailData[key]}`
              // serviceDataId: id,
              // serviceAttributeValue: detailData[key]
            }).then((res) => {
              if (
                res.success &&
                res.data &&
                res.data.length
              ) {
                this.resolvePictures(res.data[0].children)
                const tempList = []
                res.data[0].children.forEach((item) => {
                  item.pictureInfoList.forEach((child) => {
                    child.pictureType = item.catalogName
                    tempList.push(child)
                  })
                })
                this.propertyDetailPictures = tempList
                console.log('图片', res.data)
                console.log(
                  'flatten',
                  this.propertyDetailFlattenPictures
                )
              }
            })
            this.multiDetailVisible = false
            this.propertyDetailVisible = true
            this.currentPropertyDetailTabIndex = 0
          } else {
            this.$message.error('无数据服务配置')
          }
        } else {
          this.$message.error('无数据服务配置')
        }
      }
    },
    // 缩放定位
    zoomPositioning() {
      // console.log(this.cartographic)
      // console.log(mapViewer[this.viewerId])
      // 数字孪生部分缩放的视角高度略高，因为bim模型加载存在高度
      let height = 3000
      if (
        this.$route.path.indexOf('/cockpit/digitaltwin') !==
        -1
      ) {
        height = 5000
      }
      mapViewer[this.viewerId].camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          Cesium.Math.toDegrees(
            this.cartographic.longitude
          ),
          Cesium.Math.toDegrees(this.cartographic.latitude),
          this.cartographic.height + height
        )
      })
    },
    // 属性复制
    copyProperty(e) {
      // console.log(this.multiDetailData[this.multiDetailIndex].detailData)
      const copied_text = window.getSelection().toString()
      const text = copied_text.replaceAll(': ', '\t')
      // let text = ''
      // const data = this.multiDetailData[this.multiDetailIndex].detailData
      // for (const key in data) {
      //   if (key.indexOf('SM') === -1 &&
      //     key.indexOf('Sm') === -1 &&
      //     key.indexOf('sm') === -1) {
      //     text += key + '\t'
      //     text += data[key] + '\n'
      //   }
      // }
      this.$copyText(text).then(
        (res) => {
          this.$message.success('复制成功')
        },
        (err) => {
          this.$message.error('复制失败')
        }
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.multi-detail {
  position: absolute;
  //top: 50%;
  //left: 50%;
  width: 410px;
  height: 350px;
  //transform: translateX(-50%) translateY(-50%);
  background-color: #192f3de6;
  display: flex;
  flex-direction: column;

  &-header {
    width: 100%;
    height: 43px;
    background: #00ccff7f;
    padding: 16px 6px 16px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-title {
      flex: 1;
      font-size: 16px;
      font-weight: 800;
      margin-right: 10px;
    }

    &-close {
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
    }

    &-right {
      position: absolute;
      right: 10px;
      top: 43px;
      display: flex;
      align-items: center;
    }
  }

  &-content {
    flex: 1;
    overflow: hidden;
    padding: 16px;

    .el-scrollbar {
      height: 83%;
      margin-bottom: 12px;
    }

    .can-copy-content {
      user-select: text;
      -webkit-user-select: text;
      --ms-user-select: text;
      -ms-user-select: text;
    }

    .button-box {
      display: flex;
      justify-content: space-around;
    }

    ::v-deep {
      .el-button {
        width: 120px;
        height: 36px;
        background-color: rgba(0, 0, 0, 0);
        border: 1px solid #d2e6f0;
        color: #ffffff;
        border-radius: 4px;
        padding: 0 20px;
        //margin-left: 42px;
        //line-height: 36px;

        //&.disable {
        //  cursor: not-allowed;
        //}
      }

      .el-button.active {
        border-radius: 4px;
        border-color: rgba(0, 210, 255, 1);
        background-color: rgba(0, 210, 255, 1);
      }

      .el-button:hover {
        border-radius: 4px;
        border-color: rgba(0, 210, 255, 1);
        background-color: rgba(0, 210, 255, 1);
      }

      .el-scrollbar__wrap {
        overflow-x: hidden;

        .el-scrollbar__view {
          height: 100%;
        }
      }
    }

    &-item {
      display: flex;
      align-items: center;
      cursor: text;

      .name {
        font-size: 14px;
        font-weight: 500;
        color: #d2e6f0;
        //user-select: auto;
        //-webkit-user-select: auto;
        //--ms-user-select: auto;
        //-ms-user-select: auto;
      }

      .value {
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
        margin-left: 8px;
        //user-select: auto;
        //-webkit-user-select: auto;
        //--ms-user-select: auto;
        //-ms-user-select: auto;
      }
    }

    &-control {
      display: flex;
      align-items: center;
      margin-top: 10px;
    }
  }
}
.property-detail {
  position: absolute;
  display: flex;
  flex-direction: column;
  top: 0px;
  right: 47px;
  bottom: 0;
  width: 400px;
  background: linear-gradient(
    90deg,
    rgba(25, 47, 61, 0.1),
    rgba(25, 47, 61, 0.9)
  );

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    color: #fff;

    &-left {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 10px;
      padding-top: 10px;

      &-title {
        font-size: 16px;
        font-weight: 800;
      }

      .tab {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;

        &-item {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 10px;
          cursor: pointer;
          width: 114px;
          height: 28px;
          font-size: 14px;
          font-weight: 600;
          color: white;

          &.active {
            font-weight: 800;
            background-image: url('~@/assets/img/project_info_item_bg.png');
            background-size: contain;
            background-repeat: no-repeat;
          }
        }
      }
    }

    .close {
      padding: 10px;
      cursor: pointer;
    }
  }

  &-body {
    flex: 1;
    overflow: hidden;

    .el-scrollbar {
      height: 100%;
    }

    ::v-deep {
      .el-scrollbar__wrap {
        overflow-x: hidden;

        .el-scrollbar__view {
          height: 100%;
          padding: 10px;
        }
      }
    }

    .attachment-container {
      display: flex;
      height: 100%;

      .left {
        display: flex;
        flex-direction: column;
        width: 117px;
        min-width: 117px;
        max-width: 117px;

        .stage {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 42px;
          cursor: pointer;
          font-size: 14px;

          &.active {
            border-left: 2px solid #00d2ff;
            background-color: rgba(46, 151, 211, 0.1);
            color: #00d2ff;
          }
        }
      }

      .right {
        flex: 1;
        overflow-x: hidden;
        display: flex;
        flex-direction: column;
        background: rgba(46, 151, 211, 0.2);

        .node {
          display: flex;
          flex-direction: column;

          &:not(:last-of-type) {
            margin-bottom: 28px;
          }

          &-name {
            display: flex;
            align-items: center;

            .prefix {
              width: 4px;
              height: 12px;
              background: #2e97d3;
              border-radius: 2px;
            }

            span {
              flex: 1;
              font-size: 14px;
              font-weight: 500;
              color: #fefefe;
              margin-left: 10px;
            }
          }

          &-child {
            margin-left: 14px;
            font-size: 14px;
            font-weight: 500;

            ::v-deep {
              .el-link.el-link--default {
                width: auto;
                max-width: 100%;
                overflow-x: hidden;

                .el-link--inner {
                  display: flex;
                  align-items: center;
                  width: 100%;

                  i {
                    color: #fefefe;
                  }

                  span {
                    flex: 1;
                    color: #fefefe;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  }
                }
              }
            }

            &.first {
              margin-top: 20px;
            }
          }
        }
      }
    }

    .picture {
      display: flex;
      flex-direction: column;

      &-header {
        display: flex;
        align-items: center;

        .prefix {
          width: 4px;
          height: 12px;
          background: #2e97d3;
          border-radius: 2px;
        }

        .type {
          font-size: 14px;
          color: #fefefe;
          font-weight: 500;
          margin-left: 10px;
        }

        .count {
          font-size: 12px;
          color: #d2e6f0;
          margin-left: 15px;
        }
      }

      &-list {
        display: grid;
        grid-template-columns: repeat(2, auto);
        row-gap: 12px;
        column-gap: 9px;
        margin-top: 16px;
        margin-bottom: 30px;

        &-item {
          position: relative;
          width: calc((400px - 10px * 2 - 10px) / 2);
          height: 132px;
          cursor: pointer;

          .el-image {
            width: 100%;
            height: 100%;
          }

          .time {
            position: absolute;
            top: 3px;
            left: 3px;
            font-size: 12px;
            font-weight: 500;
            color: #d2e6f0;
          }

          .introduction {
            position: absolute;
            bottom: 3px;
            left: 3px;
            right: 3px;
            font-size: 12px;
            font-weight: 500;
            color: #d2e6f0;
          }
        }
      }
    }
  }
}
</style>
